package com.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 更新令牌定时服务
 */
@Service
public class TokenUpdateService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.secret}")
    private String secret;


    @Value("${baidu.appid}")
    private  String  baiduAppid;

    @Value("${baidu.serect}")
    private  String baiduSerect;


    /**
     * 第一次执行是启动Tomcat后2毫秒就执行,以后每隔30分钟执行一次
     */
    @Scheduled(initialDelay = 2, fixedRate = 180000)
    public void updateToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
        String newUrl = String.format(url, appid, secret);
        String result = restTemplate.getForObject(newUrl, String.class);
        //System.out.println(result);
        String token = JSONObject.parseObject(result).getString("access_token");
        redisTemplate.boundValueOps("token").set(token);
    }

    @Scheduled(initialDelay = 3, fixedRate =180000)
    public void updateBaiduToken()
    {
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s";
        String newUrl = String.format(url,baiduAppid,baiduSerect);
        String result = restTemplate.getForObject(newUrl,String.class);

        System.out.println("#"+result+"$");
    }

}
